package com.un.ebs.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.WebResult;
import com.un.ebs.core.util.WebUtils;
import com.un.ebs.sys.domain.*;
import com.un.ebs.sys.dto.AppTenantAddDto;
import com.un.ebs.sys.dto.AppTenantUpdateDto;
import com.un.ebs.sys.mapper.AppTenantExtMapper;
import com.un.ebs.sys.mapper.PersonnelExtMapper;
import com.un.ebs.sys.mapper.TenantAdminMapper;
import com.un.ebs.sys.mapper.UserMapper;
import com.un.ebs.sys.service.AppTenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liubo
 * @since 2019-09-15
 */
@RestController
@RequestMapping("/appTenant")
@Api(value = "sys-app-tenant", description = "租户")
public class AppTenantController {

    @Autowired
    private AppTenantService service;

    @Autowired
    private AppTenantExtMapper appTenantExtMapper;

    @Autowired
    private PersonnelExtMapper personnelExtMapper;

    @Autowired
    private TenantAdminMapper tenantAdminMapper;

    @Resource
    private UserMapper userMapper;

    @PostMapping("add")
    @ApiOperation(value = "add", notes = "添加")
    public WebResult save(@RequestBody AppTenantAddDto req) {
        service.add(req);
        return WebUtils.success();
    }

    @PostMapping("addAdmin")
    @ApiOperation(value = "addAdmin", notes = "添加现有用户为租户管理员")
    public WebResult addAdmin(@RequestParam String tenantId, @RequestParam String userId) {
        service.addAdmin(tenantId, userId);
        return WebUtils.success();
    }

    @PostMapping("createAdmin")
    @ApiOperation(value = "createAdmin", notes = "创建新的租户管理员")
    public WebResult createAdmin(@RequestParam String tenantId, @RequestParam String userName, @RequestParam String password, @RequestParam String personnelName, @RequestParam String phone) {
        service.addAdmin(tenantId, userName, password, personnelName, phone);
        return WebUtils.success();
    }

    @PostMapping("update")
    @ApiOperation(value = "update", notes = "修改")
    public WebResult update(@RequestBody AppTenantUpdateDto req) {
        service.update(req);
        return WebUtils.success();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "getById", notes = "根据主键获取单个 AppTenant")
    public WebResult getById(@PathVariable("id") String id) {
        return WebUtils.success(service.queryById(id));
    }

    @GetMapping("list/{appId}")
    @ApiOperation(value = "list", notes = "根据AppId获取租户列表")
    public WebResult<AppTenantExt> list(@PathVariable("appId") String appId) {
        LambdaQueryWrapper<AppTenantExt> lq = Wrappers.lambdaQuery();
        lq.eq(AppTenantExt::getAppId, appId);
        return WebUtils.success(appTenantExtMapper.selectList(lq));
    }

    @GetMapping("listAdmin")
    @ApiOperation(value = "listAdmin", notes = "根据AppId获取租户列表")
    public WebResult<List<PersonnelExt>> listAdmin(@RequestParam String tenantId) {
        LambdaQueryWrapper<TenantAdmin> lq = Wrappers.lambdaQuery();
        lq.eq(TenantAdmin::getTenantId, tenantId);

        List<TenantAdmin> admins = tenantAdminMapper.selectList(lq);
        if (admins.stream().map(s -> s.getUserId()).distinct().toArray().length <= 0) {
            return WebUtils.success();
        }
        LambdaQueryWrapper<PersonnelExt> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(PersonnelExt::getUserId, admins.stream().map(s -> s.getUserId()).distinct().collect(Collectors.toList()));
        queryWrapper.orderByAsc(PersonnelExt::getSort);
        List<PersonnelExt> ret = personnelExtMapper.selectList(queryWrapper);

        for (TenantAdmin item : admins) {
            PersonnelExt obj = new PersonnelExt();
            User user = userMapper.selectById(item.getUserId());
            if (user != null) {
                if (user.getIsDelete()) {
                    continue;
                }
                if (ret.stream().filter(s -> s.getUserId().equals(user.getId())).count() > 0) {
                    continue;
                }
                obj.setUserId(user.getId());
                obj.setUserName(user.getUserName());
                ret.add(obj);
            }
        }
        return WebUtils.success(ret);
    }

    @GetMapping("listUser")
    @ApiOperation(value = "listUser", notes = "根据AppId获取租户列表")
    public WebResult<PersonnelExt> listUser(@RequestParam String entId) {
        LambdaQueryWrapper<PersonnelExt> lq = Wrappers.lambdaQuery();
        lq.eq(PersonnelExt::getEntId, entId);
        lq.eq(PersonnelExt::getIsDelete, false);
        lq.isNotNull(PersonnelExt::getUserId);
        lq.orderByAsc(PersonnelExt::getSort);
        return WebUtils.success(personnelExtMapper.selectList(lq));
    }

    @PostMapping("deleteAdmin")
    @ApiOperation(value = "deleteAdmin", notes = "删除租户管理员")
    public WebResult deleteAdmin(@RequestParam String tenantId, @RequestParam String userId) {
        AppTenant tenant = service.queryById(tenantId);
        if (tenant == null) {
            return WebUtils.success();
        }
        if (tenant.getCreateAt().equals(userId)) {
            throw new BusinessException("此账号为租户创建者，不能删除。");
        }
        service.deleteAdmin(tenantId, userId);
        return WebUtils.success();
    }

    @PostMapping("delete/{id}")
    @ApiOperation(value = "delete", notes = "根据主键删除单个 AppTenant")
    public WebResult delete(@PathVariable("id") String id) {
        service.delete(id);
        return WebUtils.success();
    }
}